package com.bigevent.controller;
import com.bigevent.pojo.User;
import com.bigevent.service.UserService;
import com.bigevent.utils.JwtUtil;
import com.bigevent.pojo.Result;
import com.bigevent.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.bigevent.utils.Md5Util;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@Validated //参数检验注解
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @PostMapping("/register")
    public Result register(@Pattern(regexp="^\\S{5,16}$")String username, @Pattern(regexp="^\\S{5,16}$")String password){
        User user = userService.findByUserName(username);
        if(user == null) {
            userService.register(username,password);
            return Result.success();
        }
        else {
            return Result.error("用户名已存在");
        }
    }

    @PostMapping("/login")
    public Result login(@Pattern(regexp="^\\S{5,16}$")String username, @Pattern(regexp="^\\S{5,16}$")String password) {
        User loginUser = userService.findByUserName(username);
        if(loginUser == null) {
            return Result.error("用户名不存在");
        }
        if(Md5Util.getMD5String(password).equals(loginUser.getPassword())) {//验证密码正确
            //如果登录成功生成jwt令牌
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", loginUser.getId());
            claims.put("username", loginUser.getUsername());
            String token = JwtUtil.createToken(claims);//添加载荷
            //将token作为键和值存储在Redis中
            //创建Redis操作集合
            ValueOperations<String,String> ops = stringRedisTemplate.opsForValue();
            ops.set(token,token,12, TimeUnit.HOURS);
            return Result.success(token);
        }
        return Result.error("密码错误");
    }


//    @GetMapping("/userInfo")
//    public Result<User> userInfo(@RequestHeader(name = "Authorization") String token){
//        Map<String,Object> map = JwtUtil.parseToken(token);
//        String username = (String) map.get("username");
//        User user = userService.findByUserName(username);
//        return Result.success(user);
//    }
    //使用ThreadLocal复用拦截器里面的token解析

    @GetMapping("/userInfo")
    public Result<User> userInfo(){
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User user = userService.findByUserName(username);
        return Result.success(user);
    }

    //@RequestBody 用于获取请求体中的内容

    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user){
        userService.update(user);
        return Result.success();
    }

    //RequestParam用于获取查询参数或表单数据
    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl){
        userService.updateAvatar(avatarUrl);
        return Result.success();
    }

    @PatchMapping("/updatePassword")
    public Result updatePassword(@RequestBody Map<String,Object> params,@RequestHeader("Authorization") String token){
        //手动校验参数
        String oldPassword = (String) params.get("oldPassword");
        String newPassword = (String) params.get("newPassword");
        String rePassword = (String) params.get("rePassword");

        if(!StringUtils.hasLength(oldPassword) || !StringUtils.hasLength(newPassword) || !StringUtils.hasLength(rePassword)){
            return Result.error("参数错误");
        }
        //第一步
        //确认输入的原密码是否正确
        //先从ThreadLocal中获取用户名
        //调用userService的findByName（）方法得到数据库的密码进行比对
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User logUser = userService.findByUserName(username);
        if(!logUser.getPassword().equals(Md5Util.getMD5String(oldPassword))){
            return Result.error("原密码输入错误");
        }
        //第二部 验证新密码俩次输入是否一致
        if(!newPassword.equals(rePassword)){
            return Result.error("两次密码输入不一致");
        }
        //第三步 调用数据库更新密码
        userService.updatePassword(newPassword);
        //删除Redis保存的旧令牌
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        ops.getOperations().delete(token);
        return Result.success();
    }
}
